const Cos = require("cos-nodejs-sdk-v5");
const fs = require("fs");

const cos = new Cos({
  SecretId: "AKIDJWXRAhsDB0xmX8nAPSL1Vnt7EAxYI9Bf",
  SecretKey: "Z6UmsmV7at34vgIj05yfOydDcoocFftw",
  Region: "ap-beijing",
  Bucket: "pupp-1252071497",
});

const actMap = {
  headObject: "head",
  putObject: "put",
  deleteObject: "delete",
  getObject: "get",
  getBucket: "listBuckets",
  getObjectUrl: "signatureUrl",
};
for (const action in actMap) {
  const method = actMap[action];
  const _act = "_" + action;
  Cos.prototype[_act] = function (params = {}) {
    if (!params.Bucket || !params.Region) {
      const { Bucket, Region } = this.options;
      params.Bucket = Bucket;
      params.Region = Region;
    }

    return new Promise((resolve, reject) => {
      this[action](params, (err, data) => {
        if (err) {
          let error = new Error(err.error);
          if (typeof err.error == "object") {
            const { Message, Code } = err.error;
            error = new Error(Message);
            error.name = Code;
          }
          reject(error);
        } else resolve(data);
      });
    });
  };
  Cos.prototype[method] = function (name, body, opts = {}) {
    if (/list/.test(method)) {
      return this[_act]({
        ...name,
      }); // 第一个参数为对象
    }
    if (method == "put") {
      if (typeof body == "string") body = fs.createReadStream(body);
      return this[_act]({
        Key: name,
        Body: body,
        ...opts,
      }).then((res) => {
        res.url = "https://" + res.Location;
        return res;
      });
    }
    // console.log(method, name)
    const args = {
      Key: name,
    };
    const isSign = method == "signatureUrl";
    // if (isSign) {
    //   args.Expires = 3600; // 默认900秒
    //   args.Sign = true;
    // }
    if (typeof body == "object") {
      for (const k in body) {
        args[k.capitalize()] = body[k];
      }
    }
    return this[_act](args).then((res) => {
      if (isSign) return res.Url;
      return res;
    });
  };
}

module.exports = cos;
